/*用户设置界面*/
/*组件一/q*/
class Setting extends React.Component {
    constructor (){
        super();
        this.state = {
            avatar : ''
        }
    }
    componentDidMount (){
		var wrapper=this.props.wrapper;
		if(!wrapper.state.userInfo.name){
			this.onLoad()
		}
    }
    onLoad (){
    	var wrapper=this.props.wrapper;
            $.ajax({
                type: "GET",
                url: "/community/" + wallId + "/profile",
                dataType: "json",
                success : function (data){
                    if(data && data.success){
                		wrapper.setState({
	                        userPhotoCollection : (data.data.photo_url || []),
	                        userInfo:data.data.user
	                    })
                	}
                }
            })
    }
    renderUserName () {
        var wrapper=this.props.wrapper;

        return <div className="bd" >
            <ModifyName wrapper={wrapper} />
        </div>;
    }
    renderCheckPhotos () {
        var wrapper=this.props.wrapper;

        return <div className="bd" >
            <UserPhotos wrapper={wrapper} />
        </div>;
    }
    renderAdminSetting (isAdmin) {
        var wrapper=this.props.wrapper,
            app=wrapper.props.app,
            isAdmin=app.isAdmin;

        if(isAdmin){
            return <div className="bd" >
                <AdminSetting wrapper={wrapper} />
            </div>;
        }
    }
    renderOutlinkList () {
        var wrapper=this.props.wrapper;
        
        return <div className="bd" style={{paddingBottom:'0'}} >
            <OutlinkList wrapper={wrapper} />
        </div>;
    }
    renderDefault (){
        var wrapper=this.props.wrapper,
            app=wrapper.props.app,
            isAdmin=app.isAdmin,
            isPhone=this.props.isPhone;

        return <div className="bd" >
            <UserTwo wrapper={wrapper} photo = {this}/>
            <div className="weui_cells weui_cells_access">
                {isAdmin && isPhone?<a className="weui_cell" href="#admin-setting">
                    <div className="weui_cell_bd weui_cell_primary">
                        <p>{i18next.t('profile.wall_setting.label')}</p>
                    </div>
                    <div className="weui_cell_ft"></div>
                </a>:null}
                <a className="weui_cell" href="#check-photos">
                    <div className="weui_cell_bd weui_cell_primary">
                        <span className="liAP">{i18next.t('profile.my_photos')}</span>
                        <span >( {wrapper.state.userPhotoCollection.length} )</span>
                    </div>
                    <div className="weui_cell_ft"></div>
                </a>
                {isAdmin?<a className="weui_cell weui_cells_access" href="#outlink-list">
                    <div className="weui_cell_bd weui_cell_primary">
                        <p>{i18next.t('profile.outside_chain_statistical')}</p>
                    </div>
                    <div className="weui_cell_ft"></div>
                </a>:null}
            </div>
        </div>
    }
    renderContent () {
        var self=this,
            wrapper=this.props.wrapper,
            router=wrapper.state.router;
            
        switch(router) {
            case 'userSetname':
                return this.renderUserName();
            case 'checkPhotos':
                return this.renderCheckPhotos();
            case 'adminSetting':
                return this.renderAdminSetting();
            case 'outlinkList':
                return this.renderOutlinkList();
            default:
                return this.renderDefault();
        }
    }
    render (){
    	var wrapper=this.props.wrapper,
            app=wrapper.props.app,
            isAdmin=app.isAdmin,
            router=wrapper.state.router;
        
        return(
            <div className="cell" style={{height:'100%'}}>
                {this.renderContent()}
            </div>
        );
    }
};

/*管理员设置界面*/
class AdminSetting extends React.Component {
    constructor (props){
        super(props);
		var wrapper=this.props.wrapper,
			mainTitle=wrapper.state.mainTitle,
			describe=wrapper.state.describe,
			logo=wrapper.state.logo,
			qrCode=wrapper.state.qrCode,
            template=wrapper.state.template;
        
        this.state = {
            number:describe.length || 0,
			template:template,
			mainTitle:mainTitle,
			describe:describe,
			logo:logo,
			qrCode:qrCode,
            message:'',
            logo_server_id:null,
            qrCode_server_id:null,
            uploadType:null
        }
	}
	showMenu (uploadType){
        this.takePhoto(uploadType)
	}
    takePhoto (uploadType) {
		var self = this,
            state = {};

		if(isWxReady) {
			wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有original
                sourceType: ['camera','album'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    //self.localId = localIds[0];
                    state[uploadType]=localIds[0];
                    self.setState(state)
                }
            });
		}
	}
	submit () {
        var self=this,
            wrapper=this.props.wrapper,
            state=this.state,
            asyncList=[];
        var data = {};
        if(state.logo_server_id){
            asyncList.push(function(callback){
                uploadImage(state.logo_server_id, 'logo_server_id' ,callback)
            });
        }
        
        if(state.qrCode_server_id){
            asyncList.push(function(callback){
                uploadImage(state.qrCode_server_id, 'qrCode_server_id', callback);
            });
        }

        function uploadImage(localId, name, callback){

            wx.uploadImage({
                localId:localId,
                isShowProgressTips: 1,
                success: function(res) {
                    data[name] = res.serverId;
                    callback && callback(null);
                },
                fail: function(error) {
                    callback && callback(null);
                }
            })
        }

        async.waterfall(asyncList,function(err, result){
            console.log(result);
            $.ajax({
                type:'post',
                url:'/me/walls',
                data:_.extend({
                    id:wallId,
                    app_id:appId,
                    name:state.mainTitle,
                    description:state.describe,
                    logo:state.logo,
                    qrCode:state.qrCode,
                    template:state.template
                },data),
                dataType:'json',
                success:function(data){
                    if(data.success){
                        location.hash='#home';
                        location.reload();
                        /*wrapper.setState({
                            mainTitle:state.mainTitle,
                            describe:state.describe,
                            logo:data.data.logo || state.logo_server_id,
                            qrCode:data.data.qrCode || state.qrCode_server_id,
                            template:state.template
                        });
                        location.hash='#setting'*/
                    }else{
                        self.state({
                            message:data.error
                        })
                    }
                },
                error:function(){
                    self.setState({
                        message: i18next.t('profile.failure')
                    })
                }
            })
        });

        
		/*var wrapper=this.props.wrapper;
		wrapper.setState({
			mainTitle:this.state.mainTitle,
			describe:this.state.describe
		});
		location.hash='#home'*/
	}
    inputValue (e,value){
		var state={},
			key=e.target.name,
			val=value || e.target.value;

		state[key]=val;

        if(key=='describe'){
            state.number=val.length
        }

		this.setState(state)
	}
	render (){
		var self=this,
            state=this.state,
            wrapper=this.props.wrapper,
			number=state.number,
			template=state.template,
			mainTitle=state.mainTitle,
			describe=state.describe,
			logo=state.logo,
			qrCode=state.qrCode,
            message=state.message,
            uploadType=state.uploadType;

		return (
			<div className="bd">
                <div className="weui_cells_title">{i18next.t('profile.wall.name')}</div>
			    <div className="weui_cells">
			    	<div className="weui_cell">
				        <div className="weui_cell_bd weui_cell_primary">
				            <input className="weui_input" name="mainTitle" type="text" placeholder= {i18next.t('profile.wall.picture')} value={mainTitle} onChange={this.inputValue.bind(this)} />
				        </div>
				    </div>
			    </div>
                <div className="weui_cells_title">{i18next.t('profile.wall.description')}</div>
			    <div className="weui_cells">
			        <div className="weui_cell">
			        	<div className="weui_cell_bd weui_cell_primary">
			                <textarea className="weui_textarea" name="describe" placeholder= {i18next.t('profile.wall.activity')} maxLength="140" rows="2" value={describe} onChange={this.inputValue.bind(this)}></textarea>
			                <div className="weui_textarea_counter"><span>{number}</span>/140</div>
			            </div>
			        </div>
			    </div>
                <div className="weui_cells_title">{i18next.t('profile.wall.logo')}</div>
                <div className="weui_cells weui_cells_form">
                    <div className="weui_panel">
                        <div className="weui_panel_bd">
                            <div className="weui_media_box weui_media_appmsg">
                                <div className="weui_media_bd">
                                    <h4 className="weui_media_title">{i18next.t('profile.wall.upload_logo')}</h4>
                                </div>
                                <label className = 'weui_media_hd'>
                                    <input className="weui_uploader_input" type="button" onClick={function(){self.showMenu('logo_server_id')}} />
                                    <img className="weui_media_appmsg_thumb" src={state.logo_server_id || logo} ref="tempImg" />
                                </label>
                            </div>
                        </div>
                    </div>
			    </div>
                <div className="weui_cells_title">{i18next.t('profile.wall.qr_code')}</div>
			    <div className="weui_cells weui_cells_form">
                    <div className="weui_panel">
                        <div className="weui_panel_bd">
                            <div className="weui_media_box weui_media_appmsg">
                                <div className="weui_media_bd">
                                    <h4 className="weui_media_title">{i18next.t('profile.wall.upload_qr_code')}</h4>
                                </div>
                                <label className = 'weui_media_hd'>
                                    <input className="weui_uploader_input" type="button" onClick={function(){self.showMenu('qrCode_server_id')}} />
                                    <img className="weui_media_appmsg_thumb" src={state.qrCode_server_id || qrCode} ref="tempImg2" />
                                </label>
                            </div>
                        </div>
                    </div>
			    </div>
			    <div className="weui_cells_title">{i18next.t('profile.wall.template')}</div>
		        <div className="weui_cells weui_cells_radio">
                    <label className="weui_cell weui_check_label" htmlFor="x12">
			            <div className="weui_cell_bd weui_cell_primary">
			                <p>{i18next.t('profile.wall.timeline')}</p>
			            </div>
			            <div className="weui_cell_ft">
			                <input type="radio" name="template" className="weui_check" id="x12" checked={template=='timeline'} onChange={function(e){this.inputValue(e,'timeline')}.bind(this)} />
			                <span className="weui_icon_checked"></span>
			            </div>
			        </label>
			        <label className="weui_cell weui_check_label" htmlFor="x11">
			            <div className="weui_cell_bd weui_cell_primary">
			                <p>{i18next.t('profile.wall.refreshing')}</p>
			            </div>
			            <div className="weui_cell_ft">
			                <input type="radio" className="weui_check" name="template" id="x11" checked={template=='mainlist'} onChange={function(e){this.inputValue(e,'mainlist')}.bind(this)} />
			                <span className="weui_icon_checked"></span>
			            </div>
			        </label>
                    <label className="weui_cell weui_check_label" htmlFor="x10">
			            <div className="weui_cell_bd weui_cell_primary">
			                <p>Path</p>
			            </div>
			            <div className="weui_cell_ft">
			                <input type="radio" className="weui_check" name="template" id="x10" checked={template=='path'} onChange={function(e){this.inputValue(e,'path')}.bind(this)} />
			                <span className="weui_icon_checked"></span>
			            </div>
			        </label>
			    </div>
                {message?<div className="weui_cell error_block"><div className="form-group has-error">
                    <div className="help-block">{message}</div>
                </div></div>:null}
		        <div className="weui_btn_area">
			        <div className="weui_btn weui_btn_primary" onClick={this.submit.bind(this)}>{i18next.t('profile.wall.ok')}</div>
			    </div>
			</div>
		)
	}
};

/*组件二*/
class UserTwo extends React.Component {
    changeAvatar (e){
        var self=this,
            photo=this.props.photo,
            wrapper=photo.props.wrapper,
            userInfo=wrapper.state.userInfo,
            reader=new FileReader();
        reader.onload=function(){
            var result=this.result;
            
            self.uploadAvatar(result,function(){
                userInfo.profile_image=result;
                wrapper.setState({
                    userInfo:userInfo
                })
            })
        };
        reader.readAsDataURL(e.target.files[0])
    }
    uploadAvatar (file,callback){
        $.ajax({
            type:'post',
            url:'/community/' + wallId + '/profile',
            data:{
                profile_image:file
            },
            dataType:'json',
            success:function(data){
                if(data.success){
                    callback(data)
                }else{
                    alert(i18next.t('profile.failure'))
                }
            },
            error:function(){
                alert(i18next.t('profile.failure'))
            }
        })
    }
    render (){
        var photo = this.props.photo,
        	wrapper=this.props.wrapper,
        	userInfo=wrapper.state.userInfo;

        return (
            <div className="weui_panel">
                <div className="weui_panel_bd">
                    <div className="weui_media_box weui_media_appmsg">
                        <label htmlFor="upload_avatar" className = 'weui_media_hd user-info-avatar'>
                            <input id="upload_avatar" style={{display:'none'}} type="file" onChange={this.changeAvatar.bind(this)} />
                            <img className="weui_media_appmsg_thumb" src={photo.state.avatar || userInfo.profile_image ? photo.state.avatar || userInfo.profile_image:''} />
                            <i className="glyphicon glyphicon-camera"></i>
                        </label>
                        <div className="weui_media_bd">
                            <h4 className="weui_media_title user-info-nickname">
                                <a href="#setname">
                                    {userInfo.name || '--'}
                                </a>
                                <i className="glyphicon glyphicon-pencil"></i>
                            </h4>
                            <p className="weui_media_desc">{i18next.t('profile.region')}: {userInfo.country || '-'} {userInfo.province || '-'} {userInfo.city || '-'}</p>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
};

/*修改昵称*/
class ModifyName extends React.Component {
    constructor (props){
        super(props);
        var wrapper=this.props.wrapper,
            userInfo=wrapper.state.userInfo;
        
        this.state = {
            name : userInfo.name || '',
            message : null
        }
    }
    changeName (e){
        this.setState({
            name:e.target.value
        })
    }
    submit (){
        var self=this,
            wrapper=this.props.wrapper,
            userInfo=wrapper.state.userInfo,
            originalName=userInfo.name,
            modifiedName=$.trim(this.state.name);

        if(modifiedName != originalName){
            $.ajax({
                type:'post',
                url:'/community/' + wallId + '/profile',
                data:{
                    name:modifiedName
                },
                dataType:'json',
                success:function(data){
                    if(data.success){
                        userInfo.name=modifiedName;
                        wrapper.setState({
                            userInfo:userInfo
                        },function(){
                            self.close()
                        })
                    }else{
                        self.setState({
                            message:data.error
                        })
                    }
                },
                error:function(){
                    self.setState({
                        message: i18next.t('profile.failure')
                    })
                }
            })
        }else{
            this.close()
        }
    }
    close (){
        location.hash='setting'
    }
    render (){
        var wrapper=this.props.wrapper,
            name=this.state.name,
            message=this.state.message;

        return (
            <div className="inputName weui_tab">
                <div className="weui_cells_title">{i18next.t('profile.wall.amend')}</div>
                <div className="weui_cells weui_cells_form">
                    <div className="weui_cell inputBorderSolid">
                        <div className="weui_cell_bd weui_cell_primary">
                            <input className="weui_input" type="text" value={name}  placeholder= {i18next.t('profile.wall.amend')} onChange={this.changeName.bind(this)} />
                        </div>
                    </div>
                </div>
                {message?<div className="weui_cell error_block"><div className="form-group has-error">
                    <div className="help-block">{message}</div>
                </div></div>:null}
                <div className="weui_btn_area">
			        <div className="weui_btn weui_btn_primary" onClick={this.submit.bind(this)}>{i18next.t('profile.wall.ok')}</div>
			    </div>
            </div>
        )
    }
};

class UserThree extends React.Component {
    render (){
        var event = this.props.event,
            photoUrl=event.photo_url,
            isApproved=event.status=='approved',
            itemWidth=parseInt(document.body.clientWidth/4),
            param = photoUrl.indexOf('?')>0?('&imageView2/3/w/'+itemWidth):('?imageView2/3/w/'+itemWidth);

        return (
            <li className="weui_uploader_file divUlLiImg" >
                <div className="contentImagesStyle" style={{backgroundImage : 'url('+( photoUrl )+param+')'}}></div>
                {isApproved?<i className="glyphicon glyphicon-ok-circle text-success"></i>:null}
            </li>
        );
     }
};

class UserPhotos extends React.Component {
    constructor () {
        super();
        this.state = {
            dataList : [],
            guanzhu : [],
            fensi : []
        }
    }
    render (){
    	var wrapper=this.props.wrapper,
            userPhotoCollection=wrapper.state.userPhotoCollection;

        return (
            <div>
                <div className="weui_panel">
                    <div className="weui_panel_hd">{i18next.t('profile.my_photos')}</div>
                </div>
                {userPhotoCollection.length?<div className="weui_cell weuiCellLeft">
                    <div className="weui_uploader_files ulStyle ">
                        {userPhotoCollection.map(function(event,index) {
                            return (<UserThree key={index} event={event} />);
                        })}
                        
                    </div>
                </div>:<center className="setting-no-content">
                    <i className="glyphicon glyphicon-picture"></i>
                    <p>{i18next.t('upload.no_photos')}</p>
                </center>}
            </div>
        );
    }
};

/*外链统计页面*/
class OutlinkList extends React.Component {
    constructor (){
        super();
        this.state = {
            isLoading:false,
            isComplete:false
        }
    }
    componentDidMount (){
		var self=this,
            wrapper=this.props.wrapper,
            app=wrapper.props.app;

		if(!wrapper.state.outlinkCollection.length){
			this.loadMore()
		}

        app.scrollContainer=$(window).unbind('scroll').bind('scroll',function(){
            var scrollTop = $(window).scrollTop();
            var scrollHeight = $(document).height();
            var windowHeight = $(window).height();
            if(scrollTop + windowHeight>=scrollHeight-50){
                self.loadMore()
            }
        })
    }
    loadMore (){
    	var self=this,
            wrapper=this.props.wrapper,
            isLoading=this.state.isLoading,
            isComplete=this.state.isComplete;
            
        if(!isLoading&&!isComplete){
            var collection=wrapper.state.outlinkCollection,
                last=_.last(collection) || {timestamp:''};

            this.setState({
                isLoading:true
            });

            $.ajax({
                type: "GET",
                url: "/wall/" + wallId + "/links?since="+last.timestamp+"&count=10&type=old",
                dataType: "json",
                success : function (data){
                    var state={
                        isLoading:false
                    };

                    if(data && data.success){
                        collection=collection.concat(data.data);
                        wrapper.setState({
                            outlinkCollection:collection
                        });

                        if(data.data.length<10){
                           state.isComplete=true
                        }
                    }

                    self.setState(state)
                },
                error:function(){
                    self.setState({
                        isLoading:false
                    })
                }
            })
        }
    }
    render (){
        var wrapper=this.props.wrapper,
            collection=wrapper.state.outlinkCollection,
            isLoading=this.state.isLoading,
            isComplete=this.state.isComplete;

        return (
            <div className="weui_panel">
                <div className="weui_panel_hd">{i18next.t('profile.outside_chain_statistical')}</div>
			    {collection.map(function(i,index){
                    return <OutlinkItem key={i.id} data={i} />
                })}
                {isLoading?<div className="weui_panel_hd" style={{textAlign:'center'}}>{i18next.t('loading')}</div>:<div className="weui_panel_hd" onClick={this.loadMore.bind(this)} style={{textAlign:'center'}}>{isComplete?'加载完毕':i18next.t('home.loadmore')}</div>}
            </div>
        )
    }
};

class OutlinkItem extends React.Component {
    render (){
        var data=this.props.data;
        
        return (
            <div className="outlink-item">
                <div className="weui_media_box weui_media_appmsg">
                    <div className="weui_media_hd">
                        <img className="weui_media_appmsg_thumb" src={data.photo_url+'?imageView2/3/w/100'} />
                    </div>
                    <div className="weui_media_bd">
                        <h4 className="weui_media_title">{data.additional_url || '-'}</h4>
                        <p className="weui_media_desc">{data.description || '-'}</p>
                        
                    </div>
                </div>
                <p className="weui_media_desc outlink-item-quota-box">
                    <span className="outlink-item-quota">{i18next.t('profile.statistical.click')} : <b>{data.statistics.clicks || 0}</b></span>
                    <span className="outlink-item-quota">{i18next.t('profile.statistical.like')} : <b>{data.statistics.likes || 0}</b></span>
                    <span className="outlink-item-quota">{i18next.t('profile.statistical.transform')} : <b>{data.statistics.conversions || 0}</b></span>
                </p>
            </div>
        )
    }
}